<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 报工二维码管理
 *
 * @icon fa fa-qrcode
 * @remark 为每个工人任务生成独属二维码，支持扫码报工
 */
class QrcodeManager extends Backend
{
    /**
     * 查看二维码列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = \app\admin\model\scanwork\Qrcode::with(['allocation.order', 'allocation.model.product', 'allocation.process', 'allocation.user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 生成二维码
     */
    public function generate($ids = null)
    {
        // 支持通过URL参数或POST参数传递ids
        if (!$ids) {
            $ids = $this->request->post('ids');
        }
        
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $allocation = \app\admin\model\scanwork\Allocation::get($ids);
        if (!$allocation) {
            $this->error('分工分配不存在');
        }
        
        try {
            // 检查是否已有二维码
            $existingQrcode = \app\admin\model\scanwork\Qrcode::where('allocation_id', $ids)->find();
            if ($existingQrcode) {
                $this->error('该分工已存在二维码');
            }
            
            // 生成二维码内容
            $qrContent = $this->generateQrContent($allocation);
            
            // 生成二维码图片
            $qrImage = $this->generateQrImage($qrContent, $allocation);
            
            // 保存二维码记录
            $qrcode = \app\admin\model\scanwork\Qrcode::create([
                'allocation_id' => $ids,
                'qr_content' => $qrContent,
                'qr_image' => $qrImage,
                'scan_count' => 0,
                'status' => 0,
                'createtime' => time()
            ]);
            
            $this->success('二维码生成成功', '', [
                'qrcode' => $qrcode,
                'qr_content' => $qrContent,
                'qr_image' => $qrImage
            ]);
            
        } catch (Exception $e) {
            $this->error('二维码生成失败：' . $e->getMessage());
        }
    }

    /**
     * 批量生成二维码
     */
    public function batchGenerate()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('请选择要生成二维码的分工');
        }
        
        $successCount = 0;
        $errorCount = 0;
        $errors = [];
        
        foreach ($ids as $id) {
            try {
                $allocation = \app\admin\model\scanwork\Allocation::get($id);
                if (!$allocation) {
                    $errorCount++;
                    $errors[] = "ID {$id}: 分工分配不存在";
                    continue;
                }
                
                // 检查是否已有二维码
                $existingQrcode = \app\admin\model\scanwork\Qrcode::where('allocation_id', $id)->find();
                if ($existingQrcode) {
                    $errorCount++;
                    $errors[] = "ID {$id}: 该分工已存在二维码";
                    continue;
                }
                
                // 生成二维码内容
                $qrContent = $this->generateQrContent($allocation);
                
                // 生成二维码图片
                $qrImage = $this->generateQrImage($qrContent, $allocation);
                
                // 保存二维码记录
                \app\admin\model\scanwork\Qrcode::create([
                    'allocation_id' => $id,
                    'qr_content' => $qrContent,
                    'qr_image' => $qrImage,
                    'scan_count' => 0,
                    'status' => 0,
                    'createtime' => time()
                ]);
                
                $successCount++;
                
            } catch (Exception $e) {
                $errorCount++;
                $errors[] = "ID {$id}: " . $e->getMessage();
            }
        }
        
        $message = "批量生成完成！成功：{$successCount}个，失败：{$errorCount}个";
        if (!empty($errors)) {
            $message .= "\n错误详情：\n" . implode("\n", $errors);
        }
        
        $this->success($message);
    }

    /**
     * 重新生成二维码
     */
    public function regenerate($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $qrcode = \app\admin\model\scanwork\Qrcode::get($ids);
        if (!$qrcode) {
            $this->error('二维码记录不存在');
        }
        
        try {
            $allocation = $qrcode->allocation;
            if (!$allocation) {
                $this->error('关联的分工分配不存在');
            }
            
            // 生成新的二维码内容
            $qrContent = $this->generateQrContent($allocation);
            
            // 生成新的二维码图片
            $qrImage = $this->generateQrImage($qrContent, $allocation);
            
            // 删除旧图片
            if ($qrcode->qr_image && file_exists(ROOT_PATH . 'public/' . $qrcode->qr_image)) {
                unlink(ROOT_PATH . 'public/' . $qrcode->qr_image);
            }
            
            // 更新二维码记录
            $qrcode->save([
                'qr_content' => $qrContent,
                'qr_image' => $qrImage,
                'scan_count' => 0,
                'status' => 0,
                'updatetime' => time()
            ]);
            
            $this->success('二维码重新生成成功', '', [
                'qr_content' => $qrContent,
                'qr_image' => $qrImage
            ]);
            
        } catch (Exception $e) {
            $this->error('二维码重新生成失败：' . $e->getMessage());
        }
    }

    /**
     * 下载二维码
     */
    public function download($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $qrcode = \app\admin\model\scanwork\Qrcode::get($ids);
        if (!$qrcode) {
            $this->error('二维码记录不存在');
        }
        
        $imagePath = ROOT_PATH . 'public/' . $qrcode->qr_image;
        if (!file_exists($imagePath)) {
            $this->error('二维码图片不存在');
        }
        
        $filename = 'qrcode_' . $qrcode->allocation->order->order_no . '_' . $qrcode->allocation->process->name . '.png';
        
        header('Content-Type: image/png');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        readfile($imagePath);
        exit;
    }

    /**
     * 批量下载二维码
     */
    public function batchDownload()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('请选择要下载的二维码');
        }
        
        try {
            // 创建ZIP文件
            $zip = new \ZipArchive();
            $zipFilename = 'qrcodes_' . date('YmdHis') . '.zip';
            $zipPath = ROOT_PATH . 'runtime/temp/' . $zipFilename;
            
            // 确保目录存在
            $dir = dirname($zipPath);
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            
            if ($zip->open($zipPath, \ZipArchive::CREATE) !== TRUE) {
                $this->error('无法创建ZIP文件');
            }
            
            $qrcodes = \app\admin\model\scanwork\Qrcode::with(['allocation.order', 'allocation.process'])
                ->where('id', 'in', $ids)
                ->select();
            
            foreach ($qrcodes as $qrcode) {
                $imagePath = ROOT_PATH . 'public/' . $qrcode->qr_image;
                if (file_exists($imagePath)) {
                    $filename = 'qrcode_' . $qrcode->allocation->order->order_no . '_' . $qrcode->allocation->process->name . '.png';
                    $zip->addFile($imagePath, $filename);
                }
            }
            
            $zip->close();
            
            // 输出ZIP文件
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment;filename="' . $zipFilename . '"');
            header('Cache-Control: max-age=0');
            
            readfile($zipPath);
            
            // 删除临时文件
            unlink($zipPath);
            exit;
            
        } catch (Exception $e) {
            $this->error('批量下载失败：' . $e->getMessage());
        }
    }

    /**
     * 打印二维码
     */
    public function print($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $qrcode = \app\admin\model\scanwork\Qrcode::with(['allocation.order', 'allocation.model.product', 'allocation.process', 'allocation.user'])
            ->get($ids);
        if (!$qrcode) {
            $this->error('二维码记录不存在');
        }
        
        $this->view->assign('qrcode', $qrcode);
        return $this->view->fetch();
    }

    /**
     * 扫码统计
     */
    public function scanStats()
    {
        $startDate = $this->request->get('start_date', date('Y-m-01'));
        $endDate = $this->request->get('end_date', date('Y-m-d'));
        
        $where = [];
        if ($startDate) {
            $where['createtime'] = ['>=', strtotime($startDate)];
        }
        if ($endDate) {
            $where['createtime'] = ['<=', strtotime($endDate . ' 23:59:59')];
        }
        
        $qrcodes = \app\admin\model\scanwork\Qrcode::with(['allocation.order', 'allocation.process'])
            ->where($where)
            ->select();
        
        $stats = [
            'total_qrcodes' => count($qrcodes),
            'total_scans' => $qrcodes->sum('scan_count'),
            'used_qrcodes' => $qrcodes->where('status', 1)->count(),
            'unused_qrcodes' => $qrcodes->where('status', 0)->count(),
            'avg_scans_per_qr' => count($qrcodes) > 0 ? round($qrcodes->sum('scan_count') / count($qrcodes), 2) : 0
        ];
        
        // 按工序统计
        $processStats = [];
        foreach ($qrcodes as $qrcode) {
            $processName = $qrcode->allocation->process->name;
            if (!isset($processStats[$processName])) {
                $processStats[$processName] = [
                    'count' => 0,
                    'scans' => 0,
                    'used' => 0
                ];
            }
            $processStats[$processName]['count']++;
            $processStats[$processName]['scans'] += $qrcode->scan_count;
            if ($qrcode->status == 1) {
                $processStats[$processName]['used']++;
            }
        }
        
        $this->view->assign('stats', $stats);
        $this->view->assign('processStats', $processStats);
        $this->view->assign('startDate', $startDate);
        $this->view->assign('endDate', $endDate);
        
        return $this->view->fetch();
    }

    /**
     * 生成二维码内容
     */
    private function generateQrContent($allocation)
    {
        $baseUrl = $this->request->domain();
        // 修复：二维码应该指向员工前端报工页面，而不是后台管理页面
        $reportUrl = $baseUrl . '/index/worker/scan?allocation_id=' . $allocation->id;
        
        return $reportUrl;
    }

    /**
     * 生成二维码图片
     */
    private function generateQrImage($content, $allocation)
    {
        try {
            // 使用二维码生成库
            $qrCode = new \Endroid\QrCode\QrCode($content);
            $qrCode->setSize(300);
            $qrCode->setMargin(10);
            
            // 设置二维码颜色 - 使用Color对象
            $qrCode->setForegroundColor(new \Endroid\QrCode\Color\Color(0, 0, 0));
            $qrCode->setBackgroundColor(new \Endroid\QrCode\Color\Color(255, 255, 255));
            
            // 生成图片路径
            $imageDir = 'uploads/qrcode/' . date('Y/m/d');
            $imagePath = $imageDir . '/qrcode_' . $allocation->id . '_' . time() . '.png';
            $fullPath = ROOT_PATH . 'public/' . $imagePath;
            
            // 确保目录存在
            $dir = dirname($fullPath);
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            
            // 使用Writer来保存图片
            $writer = new \Endroid\QrCode\Writer\PngWriter();
            $result = $writer->write($qrCode);
            $result->saveToFile($fullPath);
            
            return $imagePath;
            
        } catch (Exception $e) {
            throw new Exception('二维码图片生成失败：' . $e->getMessage());
        }
    }

    /**
     * 扫码报工接口
     */
    public function scanReport()
    {
        $allocationId = $this->request->get('allocation_id');
        if (!$allocationId) {
            $this->error('参数错误');
        }
        
        $allocation = \app\admin\model\scanwork\Allocation::with(['order', 'model.product', 'process', 'user'])
            ->get($allocationId);
        if (!$allocation) {
            $this->error('分工分配不存在');
        }
        
        // 更新扫码次数
        $qrcode = \app\admin\model\scanwork\Qrcode::where('allocation_id', $allocationId)->find();
        if ($qrcode) {
            $qrcode->save(['scan_count' => $qrcode->scan_count + 1]);
        }
        
        $this->view->assign('allocation', $allocation);
        return $this->view->fetch();
    }

    /**
     * 提交扫码报工
     */
    public function submitScanReport()
    {
        $allocationId = $this->request->post('allocation_id');
        $quantity = $this->request->post('quantity');
        $actualHours = $this->request->post('actual_hours', 0);
        $remark = $this->request->post('remark', '');
        
        if (!$allocationId || !$quantity) {
            $this->error('参数错误');
        }
        
        $allocation = \app\admin\model\scanwork\Allocation::get($allocationId);
        if (!$allocation) {
            $this->error('分工分配不存在');
        }
        
        try {
            // 计算工资
            $processPrice = \app\admin\model\scanwork\ProcessPrice::where([
                'process_id' => $allocation->process_id,
                'model_id' => $allocation->model_id
            ])->find();
            
            $wage = 0;
            if ($processPrice) {
                if ($allocation->work_type == 'piece') {
                    $wage = $quantity * $processPrice->price;
                } else {
                    $wage = $actualHours * $processPrice->time_price;
                }
            }
            
            // 创建报工记录
            $report = \app\admin\model\scanwork\Report::create([
                'allocation_id' => $allocationId,
                'user_id' => $allocation->user_id,
                'quantity' => $quantity,
                'actual_hours' => $actualHours,
                'wage' => $wage,
                'work_type' => $allocation->work_type,
                'quality_status' => 1, // 默认合格
                'status' => 0, // 待审核
                'remark' => $remark,
                'createtime' => time()
            ]);
            
            // 更新分工分配状态
            $allocation->save(['reported_quantity' => $allocation->reported_quantity + $quantity]);
            
            // 更新二维码状态
            $qrcode = \app\admin\model\scanwork\Qrcode::where('allocation_id', $allocationId)->find();
            if ($qrcode) {
                $qrcode->save(['status' => 1]); // 已使用
            }
            
            $this->success('报工提交成功，等待审核');
            
        } catch (Exception $e) {
            $this->error('报工提交失败：' . $e->getMessage());
        }
    }


}
